<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
// 导入消息工具
import message from "@/utils/message.js";
// 导入图标工具
import { Plus, Delete, Edit, View, Download, Share } from "@/utils/icons.js";

// 自定义简化的Resume接口，避免类型错误
interface ResumeItem {
    id: string | number;
    title: string;
    status: string;
    update_time: string;
    created_time: string;
    [key: string]: any;
}

const router = useRouter();
const store = useStore();

// 搜索表单
const searchForm = reactive({
    keyword: "",
    status: "",
});

// 简历列表加载状态
const loading = ref(false); // 先使用本地状态
// 简历列表数据
const resumeList = ref<ResumeItem[]>([]);
// 分页信息
const pagination = ref({
    total: 0,
    currentPage: 1,
    pageSize: 10,
});

// 简历类型/状态选项
const statusOptions = [
    { value: "", label: "全部" },
    { value: "0", label: "草稿" },
    { value: "1", label: "已完成" },
    { value: "2", label: "已投递" },
];

// 获取简历列表
const getResumeList = async () => {
    try {
        loading.value = true;
        // 尝试从store获取数据
        try {
            await store.dispatch("resume/getResumeList", {
                page: pagination.value.currentPage,
                size: pagination.value.pageSize,
                keyword: searchForm.keyword,
                status: searchForm.status,
            });

            // 如果成功从store获取数据，则更新本地状态
            if (store.state.resume) {
                // 使用类型断言避免类型错误
                resumeList.value = (store.state.resume.resumeList || []) as ResumeItem[];
                pagination.value = {
                    ...pagination.value,
                    total: store.state.resume.pagination?.total || 0,
                };
            }
        } catch (error) {
            console.error("从store获取数据失败，使用模拟数据", error);
            // 如果store访问失败，使用模拟数据
            resumeList.value = mockResumeData.value;
        }
    } catch (error) {
        console.error("获取简历列表失败", error);
        message.error("获取简历列表失败，显示模拟数据");
        resumeList.value = mockResumeData.value;
    } finally {
        loading.value = false;
    }
};

// 创建新简历
const createNewResume = () => {
    router.push({
        path: "/user/resumeInfo",
    });
};

// 查看简历详情
const viewResume = (id: string | number) => {
    router.push({
        path: "/user/resumeInfo",
        query: { id: id.toString() },
    });
};

// 编辑简历
const editResume = (id: string | number) => {
    router.push({
        path: "/user/resumeInfo",
        query: { id: id.toString(), edit: "true" },
    });
};

// 删除简历
const deleteResumeById = (id: string | number) => {
    message
        .confirm("确定要删除该简历吗？删除后将无法恢复。", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(async () => {
            try {
                await store.dispatch("resume/deleteResume", id);
                message.success("删除成功");
                // 如果删除后当前页没有数据了，则回到上一页
                if (resumeList.value.length === 1 && pagination.value.currentPage > 1) {
                    handleCurrentChange(pagination.value.currentPage - 1);
                } else {
                    getResumeList();
                }
            } catch (error) {
                console.error("删除简历失败", error);
                message.error("删除失败");
            }
        })
        .catch(() => {});
};

// 下载简历
const downloadResume = (row: any) => {
    // 此处应调用下载API，这里只是示例
    message.success(`正在下载简历 ${row.title}`);
};

// 投递简历
const submitResumeToJob = (id: string | number) => {
    router.push({
        path: "/user/submitResume",
        query: { resumeId: id.toString() },
    });
};

// 页码变化
const handleCurrentChange = (currentPage: number) => {
    pagination.value.currentPage = currentPage;
    getResumeList();
};

// 每页条数变化
const handleSizeChange = (pageSize: number) => {
    pagination.value.pageSize = pageSize;
    pagination.value.currentPage = 1;
    getResumeList();
};

// 搜索简历
const handleSearch = () => {
    pagination.value.currentPage = 1;
    getResumeList();
};

// 重置搜索
const resetSearch = () => {
    searchForm.keyword = "";
    searchForm.status = "";
    handleSearch();
};

// 格式化简历状态
const formatStatus = (status: string | number): string => {
    const statusMap: Record<string, string> = {
        "0": "草稿",
        "1": "已完成",
        "2": "已投递",
    };
    return statusMap[status.toString()] || "未知状态";
};

// 格式化更新时间
const formatDate = (date: string): string => {
    if (!date) return "";
    return new Date(date).toLocaleString();
};

// 如果没有简历数据，返回模拟数据用于展示
const mockResumeData = computed(() => {
    // 当没有实际数据时，返回模拟数据
    return [
        {
            id: "1",
            title: "前端开发工程师简历",
            status: "1",
            update_time: "2025-05-10T10:30:00",
            created_time: "2025-05-01T08:15:00",
        },
        {
            id: "2",
            title: "实习生应聘简历",
            status: "2",
            update_time: "2025-04-25T15:20:00",
            created_time: "2025-04-20T09:00:00",
        },
        {
            id: "3",
            title: "校园招聘简历模板",
            status: "0",
            update_time: "2025-04-15T11:45:00",
            created_time: "2025-04-15T11:45:00",
        },
    ];
});

onMounted(() => {
    getResumeList();
});
</script>

<template>
    <div class="resume-container">
        <div class="page-header">
            <h2>我的简历</h2>
            <el-button type="primary" @click="createNewResume" :icon="Plus"> 创建新简历 </el-button>
        </div>

        <!-- 搜索区域 -->
        <div class="search-container">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item>
                    <el-input
                        v-model="searchForm.keyword"
                        placeholder="搜索简历标题"
                        clearable
                        @keyup.enter="handleSearch"
                    />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.status" placeholder="简历状态" clearable>
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 简历列表 -->
        <el-table
            :data="resumeList.length > 0 ? resumeList : mockResumeData"
            style="width: 100%"
            v-loading="loading"
            border
            row-key="id"
            class="resume-table"
        >
            <el-table-column prop="title" label="简历标题" min-width="180">
                <template #default="{ row }">
                    <span class="resume-title" @click="viewResume(row.id)">{{ row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="row.status === '0' ? 'info' : row.status === '1' ? 'success' : 'warning'">
                        {{ formatStatus(row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="update_time" label="更新时间" width="180">
                <template #default="{ row }">
                    {{ formatDate(row.update_time) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" @click="viewResume(row.id)" :icon="View" text>查看</el-button>
                    <el-button size="small" type="primary" @click="editResume(row.id)" :icon="Edit" text
                        >编辑</el-button
                    >
                    <el-button size="small" type="success" @click="submitResumeToJob(row.id)" :icon="Share" text
                        >投递</el-button
                    >
                    <el-button size="small" type="info" @click="downloadResume(row)" :icon="Download" text
                        >下载</el-button
                    >
                    <el-button size="small" type="danger" @click="deleteResumeById(row.id)" :icon="Delete" text
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="pagination-container">
            <el-pagination
                v-if="pagination.total > 0"
                background
                layout="prev, pager, next, sizes"
                :current-page="pagination.currentPage"
                :page-size="pagination.pageSize"
                :total="pagination.total"
                :page-sizes="[10, 20, 50]"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
            />
        </div>

        <!-- 无数据时显示 -->
        <div v-if="resumeList.length === 0 && !loading" class="empty-block">
            <el-empty description="暂无简历，点击创建一份新简历">
                <el-button type="primary" @click="createNewResume">立即创建</el-button>
            </el-empty>
        </div>
    </div>
</template>

<style scoped>
.resume-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}

.page-header h2 {
    margin: 0;
    color: #333;
    font-size: 20px;
    font-weight: 600;
}

.search-container {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 6px;
}

.resume-table {
    margin-bottom: 20px;
    border-radius: 6px;
    overflow: hidden;
}

.resume-title {
    color: #1890ff;
    cursor: pointer;
    font-weight: 500;
    text-decoration: none;
}

.resume-title:hover {
    text-decoration: underline;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

/* 修复表格样式 */
:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table--border) {
    border-radius: 6px;
}

:deep(.el-button--text) {
    padding: 4px 8px;
}

:deep(.el-button--text:hover) {
    background-color: rgba(64, 158, 255, 0.1);
    border-radius: 4px;
}

.empty-block {
    padding: 40px 0;
}

@media screen and (max-width: 768px) {
    .search-form {
        display: flex;
        flex-direction: column;
    }

    .search-form .el-form-item {
        margin-right: 0;
        margin-bottom: 10px;
        width: 100%;
    }

    .search-form .el-input,
    .search-form .el-select {
        width: 100%;
    }
}
</style>
